package com.cm.service.impl;
import com.cm.mapper.EmpExprMapper;
import com.cm.mapper.EmpLogMapper;
import com.cm.mapper.EmpMapper;
import com.cm.pojo.*;
import com.cm.service.EmpLogService;
import com.cm.service.EmpService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;


/**
 * ClassName:  EmpServiceImpl
 * Package: com.cm.service.impl
 * Description:
 *
 * @Author:
 * @Create: 2025/8/10  4:13
 * @Version 1.0
 */

@Service
public class EmpServiceImpl implements EmpService{
@Autowired
private EmpMapper empMapper;
@Autowired
private EmpExprMapper empExprMapper;
//研究的是事务的传播，主要是在业务的Service类中，调用了EmpService类中的方法，那么事务就会生效
@Autowired
private EmpLogService empLogService;


/**
 *
 * 原始分页查询
 */
//    @Override
//    public PageResult<Emp> list(Integer page, Integer pageSize) {
//        Long total = empMapper.count();
//        Integer start = (page - 1) * pageSize;
//        List<Emp> rows = empMapper.list(start, pageSize);
//        return new PageResult<>(total, rows);
//    }

// 分页插件查询
@Override
public PageResult<Emp> list(EmpQueryParam param) {
    //1.获取参数
    PageHelper.startPage(param.getPage(),param.getPageSize());
    //2.执行查询
    List<Emp> rows=empMapper.list(param.getName(), param.getGender(), param.getBegin(), param.getEnd());

    //3.向下转型，强转，封装结果
    Page<Emp> empPage = (Page<Emp>) rows;
    return new PageResult<>(empPage.getTotal(), rows);
}

@Transactional(rollbackFor = Exception.class)
    @Override
    public void save(Emp emp) {
    try {
        //1.保存基本信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.save(emp);
        //保存员工经历信息
        //3. 保存员工的工作经历信息 - 批量
        Integer empId = emp.getId();
        List<EmpExpr> exprList = emp.getExprList();
//             int i = 5/0;
        if(!CollectionUtils.isEmpty(exprList)){
            exprList.forEach(empExpr -> empExpr.setEmpId(empId));
            empExprMapper.insertBatch(exprList);
        }
    } finally {
        //3.保存操作日志
        EmpLog empLog = new EmpLog(null, LocalDateTime.now(), "添加员工信息：" + emp);
        empLogService.insertLog(empLog);


    }

}

@Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Integer> ids) {
        //1.批量删除员工信息
        empMapper.delete(ids);

        //2.批量删除员工工作经历信息
        empExprMapper.delete(ids);
    }

    @Override
    public Emp getInfor(Integer id) {
        return empMapper.getInfor(id);
    }
}
